<?php
namespace catchAdmin\stock\model\search;
use catchAdmin\stock\model\Pick;
use catchAdmin\stock\model\Stock;
use catchAdmin\storehouse\model\InventoryOperationRecord;
use catchAdmin\storehouse\model\Tray;
use think\facade\Db;

trait StockSearch
{
    public function searchStockIdAttr($query, $value, $data)
    {
        return $query->whereLike('s.stock_id', $value);
    }

    public function searchTrayIdAttr($query, $value, $data)
    {
        return $query->whereLike('s.tray_id', $value);
    }

    public function searchGoodsNameAttr($query, $value, $data)
    {
        return $query->whereLike('s.goods_name', $value);
    }
    public function searchSplitStatusAttr($query, $value, $data)
    {
        return $query->where('s.split_status', $value);
    }
    public function searchStatusAttr($query, $value, $data)
    {
        return $query->where('s.status', $value);
    }
    public function searchEntrepotNameAttr($query, $value, $data)
    {
        return $query->where('s.entrepot_name', $value);
    }

    public function searchArbitraryCodeAttr($query, $value, $data){
        return $query->where('s.tray_id|s.box_id|s.slice_id|s.goods_name','like',"%$value%");
    }

    //入库时间段
    public function searchStockInTimeAttr($query, $value, $data)
    {
        if(!empty($value)){
            //$ids = (new Tray)->where('status','1')->whereBetweenTime('created_at', $value[0], $value[1])->column('warehousing_id');
            //$ids2 = (new Stock)->whereBetweenTime('created_at', $value[0], $value[1])->column('warehousing_id');

            //$where_ids = array_merge($ids,$ids2);
            //dd($ids);
            //$query->where('s.warehousing_id', 'in', $where_ids)->whereBetweenTime('s.created_at', $value[0], $value[1]);
            $query->whereBetweenTime('s.created_at', $value[0], $value[1]);
        }
    }

    //出库时间段
    public function searchStockOutTimeAttr($query, $value, $data)
    {
//        if(!empty($value)){
//            $ids = (new Tray)->where('status',3)->whereBetweenTime('created_at', $value[0], $value[1])->column('warehousing_id');
//            $query->where('s.warehousing_id', 'in', $ids);
//        }
        if(!empty($value)){
            $ids = (new Pick)->where('status',1)
                ->whereBetweenTime('updated_at', $value[0], $value[1])->column('stock_id');
            $ids2 = (new InventoryOperationRecord)->where('order_type',5)->whereBetweenTime('created_at', $value[0], $value[1])->column('stock_id');

            $ids2_arr = [];
            foreach ($ids2 as $i){
                $ids2_arr =  array_merge($ids2_arr,explode(',',$i));
            }

            $where_ids = array_merge($ids,$ids2_arr);
            $where_ids = array_values(array_unique(array_filter($where_ids)));

            $query->where('s.stock_id', 'in', $where_ids);
        }
    }

    //项号
    public function searchBatchNumberAttr($query, $value, $data)
    {
        return $query->whereLike('s.batch_number', $value);
    }
}